package com.scqzy.shengchunqiang.structure;

import java.util.*;

public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;

    TreeNode() {
    }

    public TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

    public static TreeNode array2Treenode(int[] arr) {
        TreeNode treeNode = new TreeNode(arr[0]);
        Deque<TreeNode> deque = new ArrayDeque<>();
        deque.offer(treeNode);
        int i = 1;
        while (i < arr.length && !deque.isEmpty()) {
            TreeNode poll = deque.poll();
            poll.left = new TreeNode(arr[i++]);
            if (i == arr.length) {
                break;
            }
            poll.right = new TreeNode(arr[i++]);
            deque.offer(poll.left);
            deque.offer(poll.right);
        }
        return treeNode;
    }

    public static void print(TreeNode treeNode) {
        Deque<TreeNode> deque = new ArrayDeque<>();
        List<Integer> list = new ArrayList<>();
        deque.offer(treeNode);
        while (!deque.isEmpty()) {
            TreeNode poll = deque.poll();
            list.add(poll.val);
            if (Objects.nonNull(poll.left)) {
                deque.offer(poll.left);
            }
            if (Objects.nonNull(poll.right)) {
                deque.offer(poll.right);
            }
        }
        System.out.println(list);
    }
}
